<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/12/21
 * Time: 14:53
 */
namespace App\Utils;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use App\Http\Model\Mysql\SmsLog;

class SendSms
{
    /**
     * 发送手机验证码
     * @param int $user_id
     * @param string $phone
     * @param bool $check
     * @param int $scene
     * @return array
     * @throws ClientException
     */
    public static function sendCode(int $user_id, string $phone, bool $check = true, int $scene = 1)
    {
        $aliyun     =   Config::get('upload');
        $rand_number=   createRandomNumber(6);
        if ($check) {
            $if_exists  =   SmsLog::where(['receive_user' => $user_id, 'receive_phone' => $phone, 'scene' => 1])->where('send_time', '>=', Carbon::now()->timestamp - 60)->exists();
            if ($if_exists) {
                return [false, '重复发送'];
            }
        }
        AlibabaCloud::accessKeyClient($aliyun['ali_oss']['access_key_id'], $aliyun['ali_oss']['access_key_secret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result =   AlibabaCloud::rpc()->product('Dysmsapi')->scheme('https')->action('SendSms')->version('2017-05-25')
                        ->method('POST')->host('dysmsapi.aliyuncs.com')->options([
                            'query' => [
                                'RegionId'      =>  'cn-hangzhou',
                                'PhoneNumbers'  =>  $phone,
                                'SignName'      =>  $aliyun['ali_oss']['message']['sign_name'],
                                'TemplateCode'  =>  $aliyun['ali_oss']['message']['template_code'],
                                'TemplateParam' =>  json_encode(['code' => $rand_number], JSON_UNESCAPED_UNICODE)
                            ],
                        ])->request();

            $result =   $result->toArray();
            if ($result['Code'] == 'OK') {
                SmsLog::create([
                    'receive_user'  =>  $user_id,
                    'receive_phone' =>  $phone,
                    'send_code'     =>  $rand_number,
                    'send_time'     =>  Carbon::now()->timestamp,
                    'expire_time'   =>  600,
                    'scene'         =>  $scene,
                ]);
                return [true, $result['RequestId']];
            } else {
                return [false, '发送失败'];
            }
        } catch (ClientException $exception) {
            return [false, $exception->getMessage()];
        } catch (ServerException $exception) {
            return [false, $exception->getMessage()];
        }
    }

    /**
     * 校验手机验证码
     * @param int $user_id
     * @param string $phone
     * @param string $check_code
     * @param int $scene
     * @return bool
     */
    public static function checkCode(int $user_id, string $phone, string $check_code, int $scene = 1)
    {
        $code_info  =   SmsLog::where(['receive_user' => $user_id, 'receive_phone' => $phone, 'scene' => $scene])->orderBy('id', 'desc')->select(['id', 'receive_user', 'receive_phone', 'send_code', 'send_time', 'expire_time'])->first();
        if (empty($code_info)) {
            return false;
        }

        if ($check_code != $code_info->send_code) {
            return false;
        }

        if (Carbon::now()->timestamp > $code_info->send_time + $code_info->expire_time) {
            return false;
        }

        return true;
    }

}
